package com.yidianyanglao.userData.controller;

import com.yidianyanglao.buyBack.mapper.BuyBackMapper;
import com.yidianyanglao.core.bean.RetBean;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.exception.CustomException;
import com.yidianyanglao.user.bean.UserBean;
import com.yidianyanglao.userData.bean.*;
import com.yidianyanglao.userData.mapper.UserDataMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * describe :   ------      ------
 * author  :        lf
 * time on  :   ${DAte}  16:22.
 * ----------------------------------------------------
 */
@Controller
public class UserDataController {

    @Resource
    private UserDataMapper udm;

    @Resource
    private BuyBackMapper bbm;

    /**
     * 获取我的幸运树
     * @param request
     * @param seriesId
     * @return
     */
    @RequestMapping("/user/myLuckyTree.json")
    @ResponseBody
    public RetBean getMyLuckyTree(HttpServletRequest request,String seriesId,String pageNum){

        UserBean userBean = (UserBean) request.getAttribute("request_user");

        String str = seriesId;
        if(!checkParameter(str)){
            throw new CustomException(Code.ERROR, "参数"+str+"均不能为空");
        }

        checkSeries(seriesId);

        LuckyTreeBean luckyTreeBean = udm.getTreeBySeriesId(userBean.getId(),seriesId);
        int begin = checkPageNum(pageNum);
        List<TreeDetailsBean> detailList = udm.getTreeDetailBySeriesId(begin,userBean.getId(),seriesId);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tree",luckyTreeBean);
        map.put("treeDetail",detailList);

        return new RetBean(Code.SUCCESS,"请求成功",map);
    }

    /**
     * 获取我的推荐列表
     * @param request
     * @param pageNum
     * @return
     */
    @RequestMapping("/user/myRecommendList.json")
    @ResponseBody
    public RetBean myRecommendList(HttpServletRequest request,String pageNum){
        UserBean userBean = (UserBean) request.getAttribute("request_user");
        String str = pageNum;
        if(!checkParameter(str)){
            throw new CustomException(Code.ERROR, "参数"+str+"均不能为空");
        }

        int begin = checkPageNum(pageNum);

        List<RecommendRecordBean> list = udm.getMyRecommendList(begin,userBean.getId());
        for(RecommendRecordBean bean:list){
            bean.setHeadpic(udm.getUserById(bean.getTouserId()).getHeadpic());
            /* 0:花匠   1：商家    2:业务员  3：管理中心 */
            if(bean.getToUserUsertype()==0){
                bean.setToUserUsertypeName("花匠");
            }else if(bean.getToUserUsertype()==1){
                bean.setToUserUsertypeName("商家");
            }else if(bean.getToUserUsertype()==2){
                bean.setToUserUsertypeName("业务员");
            }else if(bean.getToUserUsertype()==3){
                bean.setToUserUsertypeName("管理中心");
            }

        }

        return new RetBean(Code.SUCCESS,"请求成功",list);
    }

    /**
     * 获取我的消费记录
     * @param request
     * @param pageNum
     * @param seriesId
     * @param days 天数
     * @return
     */
    @RequestMapping("/user/myOrderList.json")
    @ResponseBody
    public RetBean myOrderList(HttpServletRequest request,String pageNum,String seriesId,String days){
        UserBean userBean = (UserBean) request.getAttribute("request_user");
        String str = pageNum+","+seriesId;
        if(!checkParameter(str)){
            throw new CustomException(Code.ERROR, "参数"+str+"均不能为空");
        }
        int begin = checkPageNum(pageNum);
        SeriesBean seriesBean = checkSeries(seriesId);

        Map<String,Object> map = new HashMap<>();

        if(days==null||days.equals("")||days.equals("null")){
            map.put("days",365);
        }else{
            map.put("days",days);
        }

        map.put("begin",begin);
        map.put("userId",userBean.getId());
        map.put("seriesId",seriesId);

        List<OrderBean> list = udm.getMyOrderList(map);
        for(OrderBean o:list){
            ShopBean shop = udm.getShopById(o.getShopId());
            if(shop != null){
                o.setShoppic(shop.getShoppic());
            }else{
                o.setShoppic("http://oss.188jielan.net/jielanwx/ydyl/defaultshoppic.png");
            }
        }
        return new RetBean(Code.SUCCESS,"请求成功",list);
    }

    /**
     * 获取我的种子明细
     * @param request
     * @param pageNum
     * @param name
     * @return
     */
    @RequestMapping("/user/mySeedDetails.json")
    @ResponseBody
    public RetBean mySeedDetails(HttpServletRequest request,String pageNum,String name){
        UserBean userBean = (UserBean) request.getAttribute("request_user");
        String str = pageNum;
        if(!checkParameter(str)){
            throw new CustomException(Code.ERROR, "参数"+str+"均不能为空");
        }
        int begin = checkPageNum(pageNum);

        if(name==null||name.equals("")||name.equals("null")){
            name = "";
        }
        String name_ = name+"%";

        List<SeedDetailsBean> list = udm.getMySeedDetails(begin,userBean.getId(),name_);

        return new RetBean(Code.SUCCESS,"请求成功",list);
    }

    public int checkPageNum(String pageNum){
        int begin = 0;
        if(!isPositiveInteger(pageNum)){
            throw new CustomException(Code.ERROR, "pageNum只能是正整数");
        }else{
            if(Integer.valueOf(pageNum)>1){
                begin = (Integer.valueOf(pageNum) - 1)* 10;
            }
            return begin;
        }
    }

    public SeriesBean checkSeries(String seriesId){
        SeriesBean seriesBean = udm.getSeriesById(seriesId);
        if(seriesBean==null){
            throw new CustomException(Code.ERROR, "系列ID不存在");
        }else{
            return seriesBean;
        }
    }

    public boolean isPositiveInteger(String pageNum) {
        return isMatch("^\\+{0,1}[1-9]\\d*", pageNum);
    }

    private boolean isMatch(String regex, String pageNum){
        if (pageNum == null || pageNum.trim().equals("")) {
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher isNum = pattern.matcher(pageNum);
        return isNum.matches();
    }

    public String checkDate(String str) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date date = (Date)formatter.parse(str);
            if(!str.equals(formatter.format(date))){
                throw new CustomException(Code.ERROR, "日期格式有误,示例：2016-08-08");
            }else{
                return str;
            }
        }catch(Exception e){
            throw new CustomException(Code.ERROR, "日期格式有误,示例：2016-08-08");
        }
    }

    public boolean checkParameter(String str){
        boolean b = true;
        String [] s = str.split(",");
        for(int i=0;i<s.length;i++){
            if(s[i]==null || s[i].equals("") || s[i].equals("null")){
                b = false;
            }
        }
        return b;
    }

    /**
     * 获取我的转赠数据
     * @param request
     * @param pageNum
     * @param token
     * @return
     */
    @RequestMapping("/user/myTransferringSeedList.json")
    @ResponseBody
    public RetBean myTransferringSeedList(HttpServletRequest request,String pageNum,String token){
        UserBean user = (UserBean)request.getAttribute("request_user");
        int begin = checkPageNum(pageNum);
        List<SeedDetailsBean> list= udm.getTurnSeedFetail(user.getId(),begin);
        return new RetBean(Code.SUCCESS,"请求成功",list);

    }


}
